package 并发编程12.Semaphore模块;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 信号量demo
 * @author idea
 * @data 2019/1/28
 */
public class SemaphoreDemo {

    public static void main(String[] args) throws InterruptedException {
        //创建信号量，并且赋予3个初始值
        Semaphore semaphore=new Semaphore(2);
        for(int i=0;i<10;i++){
           new Thread(new Runnable() {
               @Override
               public void run() {
                   try {
                       // 获取资源，若此时资源被用光，则阻塞，直到有线程归还资源
                       semaphore.tryAcquire(10,TimeUnit.SECONDS);
                       System.out.println(semaphore.getQueueLength());
                       System.out.println(semaphore.availablePermits());
                       System.out.println("获取资源");

                   } catch (Exception e) {
                       e.printStackTrace();
                   }
                   try {
                       Thread.sleep(3000);
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
                   semaphore.release();
                   System.out.println("释放");

               }
           }).start();
        }
    }
}
